var ContextMenu = function(id) {
    this.id = id;
};

ContextMenu.prototype.getContainer = function() {
    return document.getElementById(this.id);
};

ContextMenu.prototype.getParent = function(e, name) {
    if(e == null) {
        return null;
    }

    var p = e;

    while(true) {
        var nodeName = p.nodeName.toLowerCase();

        if(nodeName == name) {
            return p;
        }

        p = p.parentNode;

        if(p == null) {
            break;
        }
    }
    return null;
};

ContextMenu.prototype.setEnabled = function(command, enabled) {
    var container = this.getContainer();

    if(enabled == false) {
        jQuery(container).find("li[command=" + command + "]").addClass("disabled");
    }
    else {
        jQuery(container).find("li[command=" + command + "]").removeClass("disabled");
    }
};

ContextMenu.prototype.click = function(src) {
    var element = this.hide();
    var command = src.getAttribute("command");

    if(command != null && command.length > 0) {
        var handler = this[command];

        if(handler != null) {
            setTimeout(function() {
                handler(element);
            }, 200);
        }
    }
};

ContextMenu.prototype.show = function(event, target) {
    var container = this.getContainer();

    if(container != null) {
        var top = document.body.scrollTop + event.clientY;
        var left = document.body.scrollLeft + event.clientX;
        container.style.display = "block";

        if(top + container.offsetHeight > (document.body.scrollTop + document.documentElement.clientHeight)) {
            top = (top - container.offsetHeight);
        }

        if(top < document.body.scrollTop) {
            top = document.body.scrollTop;
        }

        if(left + container.offsetWidth > (document.body.scrollLeft + document.documentElement.clientWidth)) {
            left = (left - container.offsetWidth);
        }

        if(left < document.body.scrollLeft) {
            left = document.body.scrollLeft;
        }
        container.style.top = top + "px";
        container.style.left = left + "px";
        container.style.display = "block";
        this.element = target;
    }
    return this;
};

ContextMenu.prototype.hide = function(event) {
    var e = this.element;
    this.getContainer().style.display = "none";
    this.element = null;
    return e;
};

HTree.click = function(a) {
    var node = HTree.getNode(a);
    var params = HTree.getUserObject(a);

    if(params.type == "category") {
        HTree.setActive(node);

        /**
         * 不显示管理
         */
        if(params.categoryId == "0") {
            // document.getElementById("mainFrame").src = PageContext.getContextPath() + "/note/category/list.html?categoryId=" + params.categoryId;
        }
        else {
            document.getElementById("mainFrame").src = PageContext.getContextPath() + "/note/archive/list.html?categoryId=" + params.categoryId;
        }
    }
    else if(params.type == "archive") {
        HTree.setActive(node);
        document.getElementById("mainFrame").src = PageContext.getContextPath() + "/note/archive/edit.html?archiveId=" + params.archiveId;
    }
};

jQuery(function() {
    var contextMenu = new ContextMenu("tree-contextmenu");

    contextMenu.refresh = function(src) {
        HTree.reload(src);
    };

    contextMenu.categoryAdmin = function(src) {
        var userObject = HTree.getUserObject(src);
        document.getElementById("mainFrame").src = PageContext.getContextPath() + "/note/category/list.html?categoryId=" + userObject.categoryId;
    };

    contextMenu.archiveAdmin = function(src) {
        var userObject = HTree.getUserObject(src);
        document.getElementById("mainFrame").src = PageContext.getContextPath() + "/note/archive/list.html?categoryId=" + userObject.categoryId;
    };

    contextMenu.moveto = function(src) {
        var a = HTree.getAnchor(src);
        var userObject = HTree.getUserObject(src);
        var url = PageContext.getContextPath() + "/note/category/select.html?type=" + userObject.type;

        var iframe = document.getElementById("category-frame");
        iframe.src = "about:blank";
        iframe.src = url;

        jQuery("#category-panel div.button button.cancel").unbind();
        jQuery("#category-panel div.button button.ensure").unbind();
        jQuery("#category-panel div.button button.cancel").click(function() {
            jQuery("#category-panel").hide();
        });

        jQuery("#category-panel div.button button.ensure").click(function() {
            jQuery("#category-panel").hide();

            var iframe = document.getElementById("category-frame");
            var selectedId = iframe.contentWindow.getSelectedId();

            if(selectedId == null) {
                alert("请选择分类！");
                return;
            }

            if(userObject.type == "category") {
                CategoryManager.moveto(userObject.categoryId, selectedId, function() {
                    HTree.reload(HTree.getParentNode(src));
                });
            }
            else {
                ArchiveManager.moveto(userObject.archiveId, selectedId, function() {
                    HTree.reload(HTree.getParentNode(src));
                });
            }
        });

        jQuery("#category-panel div.title h4").html(a.getAttribute("title"));
        jQuery("#category-panel div.dialog").css({"top": "50px", left: "430px", "width": "400px", "height": "500px"});
        jQuery("#category-panel").show();
    };

    contextMenu.remove = function(src) {
        if(window.confirm("确定要删除吗？")) {
            var userObject = HTree.getUserObject(src);

            if(userObject.type == "category") {
                CategoryManager.remove(userObject.categoryId, function() {
                    HTree.setActive(null);
                    HTree.remove(src);
                });
            }
            else if(userObject.type == "archive") {
                ArchiveManager.remove(userObject.archiveId, function(result) {
                    HTree.setActive(null);
                    HTree.remove(src);
                });
            }
        }
    };

    jQuery("#tree-contextmenu").click(function(event) {
        var src = (event.srcElement || e.target);
        var li = contextMenu.getParent(src, "li");

        if(li == null) {
            return;
        }

        if(jQuery(li).hasClass("disabled")) {
            return;
        }
        contextMenu.click(li);
    });

    jQuery("#tree-contextmenu").hover(function() {
    }, function() {
        contextMenu.hide();
    });

    jQuery("#htree").contextmenu(function(event) {
        if(event.ctrlKey) {
            return true;
        }

        var node = HTree.getNode((event.srcElement || e.target));

        if(node == null) {
            return false;
        }

        var userObject = HTree.getUserObject(node);

        if(userObject.type == "category") {
            contextMenu.setEnabled("refresh", true);
            contextMenu.setEnabled("categoryAdmin", true);
            contextMenu.setEnabled("archiveAdmin", true);
            contextMenu.setEnabled("addArchive", true);
            contextMenu.setEnabled("addCategory", true);
        }
        else {
            contextMenu.setEnabled("refresh", false);
            contextMenu.setEnabled("categoryAdmin", false);
            contextMenu.setEnabled("archiveAdmin", false);
            contextMenu.setEnabled("addArchive", false);
            contextMenu.setEnabled("addCategory", false);
        }

        HTree.setActive(node);
        contextMenu.show(event, node);
        return false;
    });
});

if(typeof(window.FavoriteManager) == "undefined") {
    window.FavoriteManager = {};
}

FavoriteManager.build = function(list) {
    if(list == null || list.length < 1) {
        return "<div style=\"padding-top: 100px; text-align: center;\">尚未收藏任何笔记.</div>";
    }

    var b = [];

    for(var i = 0; i < list.length; i++) {
        var f = list[i];

        b[b.length] = "<div class=\"list-item\" archiveId=\"" + f.archiveId + "\">";
        b[b.length] = "<span class=\"file\"></span>";
        b[b.length] = "<div class=\"text\">" + f.title + "</div>";
        b[b.length] = "<span class=\"delete\"></span>";
        b[b.length] = "</div>";
    }
    return b.join("");
};

FavoriteManager.load = function() {
    var c = jQuery("#favorite-panel");
    var e = c.find(".panel-content");

    /**
     * 开始加载
     */
    e.html("<div style=\"padding-top: 100px; text-align: center;\">正在努力加载中, 请稍候...</div>");

    FavoriteManager.getFavorites(function() {
        e.html("<div style=\"padding-top: 100px; text-align: center;\">系统错误, 请稍后再试...</div>");
    }, function(favorites) {
        e.html(FavoriteManager.build(favorites));
    });
};

var FootprintManager = {};

FootprintManager.getDate = function(timeMillis) {
    var date = new Date();
    date.setTime(timeMillis);

    var y = date.getFullYear();
    var M = date.getMonth() + 1;
    var d = date.getDate();
    var a = "yyyy-dd-MM".split("-");

    a[0] = y;
    a[1] = (M < 10 ? "0" + M : M);
    a[2] = (d < 10 ? "0" + d : d);

    return a.join("-");
};

FootprintManager.build = function(list) {
    if(list == null || list.length < 1) {
        return "<div style=\"padding-top: 100px; text-align: center;\">尚未编辑任何笔记.</div>";
    }

    var b = [];

    for(var i = 0; i < list.length; i++) {
        var f = list[i];
        var image = null;

        if(f.images != null) {
            var array = f.images.split(",");

            if(array.length > 0) {
                image = "<img src=\"" + array[0] + "\"/>";
            }
        }

        b[b.length] = "<div class=\"note-item\" archiveId=\"" + f.archiveId + "\">";
        b[b.length] = " <div class=\"image\">" + (image || "") + "</div>";
        b[b.length] = " <div class=\"title\">" + f.title + "</div>";
        b[b.length] = " <div class=\"summary\">" + f.summary + "</div>";
        b[b.length] = " <div class=\"date\">" + this.getDate(f.updateTime) + "</div>";
        b[b.length] = "</div>";
    }
    return b.join("");
};

FootprintManager.load = function() {
    var c = jQuery("#footprint-panel");
    var e = c.find(".panel-content");

    e.html("<div style=\"padding-top: 100px; text-align: center;\">正在努力加载中, 请稍候...</div>");

    jQuery.ajax({
        "type": "get",
        "url": PageContext.getContextPath() + "/note/footprint/getFootprints.html",
        "dataType": "json",
        "error": function() {
            e.html("<div style=\"padding-top: 100px; text-align: center;\">系统错误, 请稍后再试...</div>");
        },
        "success": function(result) {
            e.html(FootprintManager.build(result.value));
        }
    });
};

var NoteBookManager = {};

NoteBookManager.show = function(categoryId, name) {
    jQuery("#tree-panel").show();
    jQuery("#main-panel").css("marginLeft", 424);

    var id = "htree";
    var url = PageContext.getContextPath() + "/note/category/getCategoryXml.html?categoryId=" + categoryId;

    HTree.config.stylePath = PageContext.getContextPath() + "/resource/htree/note/";
    var tree = new HTree.TreeNode({text: name, href: "?type=category&categoryId=" + categoryId, xmlSrc: url});

    tree.load(function() {
        HTree.setActive(null);
        this.render(document.getElementById(id));
    });
};

NoteBookManager.getDate = function(timeMillis) {
    var date = new Date();
    date.setTime(timeMillis);

    var y = date.getFullYear();
    var M = date.getMonth() + 1;
    var d = date.getDate();
    var a = "yyyy-dd-MM".split("-");

    a[0] = y;
    a[1] = (M < 10 ? "0" + M : M);
    a[2] = (d < 10 ? "0" + d : d);

    return a.join("-");
};

NoteBookManager.build = function(list) {
    if(list == null || list.length < 1) {
        return "<div style=\"padding-top: 100px; text-align: center;\">尚未编辑任何笔记.</div>";
    }

    var b = [];
    b[b.length] = "<div class=\"book-item\" categoryId=\"0\" note-name=\"我的笔记\">";
    b[b.length] = " <div class=\"image\"><img src=\"/resource/note/images/notebook.gif\"/></div>";
    b[b.length] = " <div class=\"title\">全部</div>";
    b[b.length] = " <div class=\"date\">&nbsp;</div>";
    b[b.length] = "</div>";

    for(var i = 0; i < list.length; i++) {
        var f = list[i];
        b[b.length] = "<div class=\"book-item\" categoryId=\"" + f.categoryId + "\" note-name=\"" + f.name + "\">";
        b[b.length] = " <div class=\"image\"><img src=\"/resource/note/images/notebook.gif\"/></div>";
        b[b.length] = " <div class=\"title\">" + f.name + "</div>";
        b[b.length] = " <div class=\"date\">" + this.getDate(f.createTime) + "</div>";
        b[b.length] = "</div>";
    }
    return b.join("");
};

NoteBookManager.load = function() {
    var c = jQuery("#notebook-panel");
    var e = c.find(".panel-content");

    e.html("<div style=\"padding-top: 100px; text-align: center;\">正在努力加载中, 请稍候...</div>");

    jQuery.ajax({
        "type": "get",
        "url": PageContext.getContextPath() + "/note/getNoteBooks.html",
        "dataType": "json",
        "error": function() {
            e.html("<div style=\"padding-top: 100px; text-align: center;\">系统错误, 请稍后再试...</div>");
        },
        "success": function(result) {
            e.html(NoteBookManager.build(result.value));
        }
    });
};

var ArchiveManager = {};
var CategoryManager = {};

ArchiveManager.moveto = function(archiveId, targetId, callback) {
    var params = {"archiveId": archiveId, "targetId": targetId};

    jQuery.ajax({
        "type": "post",
        "url": PageContext.getContextPath() + "/note/archive/moveto.html",
        "dataType": "json",
        "data": jQuery.param(params, true),
        "error": function() {
            alert("系统错误，请稍后再试！");
        },
        "success": function(result) {
            callback();
        }
    });
};

ArchiveManager.remove = function(archiveId, callback) {
    jQuery.ajax({
        "type": "post",
        "url": PageContext.getContextPath() + "/note/archive/delete.html",
        "dataType": "json",
        "data": "archiveId=" + archiveId,
        "error": function() {
            alert("系统错误，请稍后再试！");
        },
        "success": function(result) {
            callback();
        }
    });
};

CategoryManager.moveto = function(categoryId, targetId, callback) {
    var params = {"categoryId": categoryId, "targetId": targetId};

    jQuery.ajax({
        "type": "post",
        "url": PageContext.getContextPath() + "/note/category/moveto.html",
        "dataType": "json",
        "data": jQuery.param(params, true),
        "error": function() {
            alert("系统错误，请稍后再试！");
        },
        "success": function(result) {
            callback();
        }
    });
};

CategoryManager.remove = function(categoryId, callback) {
    jQuery.ajax({
        "type": "post",
        "url": PageContext.getContextPath() + "/note/category/delete.html",
        "dataType": "json",
        "data": "categoryId=" + categoryId,
        "error": function() {
            alert("系统错误，请稍后再试！");
        },
        "success": function(result) {
            callback();
        }
    });
};

var SliderPanel = function(id) {
    this.id = id;
    var self = this;

    jQuery("#" + id).click(function(event) {
        var src = (event.srcElement || event.target);

        if(src.className != "slider-mask") {
            return;
        }
        self.hide();
    });
};

SliderPanel.zIndex = 1000;

SliderPanel.prototype.show = function() {
    var src = jQuery("#" + this.id + " div.slider-panel");

    jQuery("#" + this.id).css("zIndex", SliderPanel.zIndex++).show();
    src.css("marginLeft", (0 - src.width()) + "px");
    src.animate({"marginLeft": 74}, "slow");
};

SliderPanel.prototype.hide = function() {
    var e = jQuery("#" + this.id + " div.slider-panel");

    e.animate({"marginLeft": 0 - e.width()}, "slow", function() {
        jQuery(this).closest("div.slider-mask").hide();
    });
};

/**
 * 新建笔记
 */
jQuery(function() {
    jQuery("#create").click(function() {
        var node = HTree.getActive();

        if(node == null) {
            alert("请选择笔记分类！");
            return;
        }

        var userObject = HTree.getUserObject(node);
        var categoryId = parseInt(userObject.categoryId);

        if(isNaN(categoryId) || categoryId < 1) {
            alert("请选择笔记分类！");
        }

        var params = {};
        params.categoryId = categoryId;
        params.title = "新建笔记";

        jQuery.ajax({
            "type": "get",
            "url": PageContext.getContextPath() + "/note/archive/create.html",
            "dataType": "json",
            "data": jQuery.param(params, true),
            "error": function() {
                alert("系统错误，请稍后再试！");
            },
            "success": function(result) {
                Response.success(result, function(archiveId) {
                    HTree.reload(node);
                    document.getElementById("mainFrame").src = PageContext.getContextPath() + "/note/archive/edit.html?archiveId=" + archiveId;
                });
            }
        });
    });
});

/**
 * 收藏
 */
jQuery(function() {
    var sliderPanel = new SliderPanel("favorite-panel");

    jQuery("#favorite").click(function() {
        FavoriteManager.load();
        sliderPanel.show();
    });

    jQuery("#favorite-panel .panel-content").click(function(event) {
        var src = (event.srcElement || event.target);
        var ele = jQuery(src).closest("div.list-item");

        if(ele.size() < 1) {
            return;
        }
        sliderPanel.hide();
        document.getElementById("mainFrame").src = PageContext.getContextPath() + "/note/archive/edit.html?archiveId=" + ele.attr("archiveId");
    });
});

/**
 * 最近编辑
 */
jQuery(function() {
    var sliderPanel = new SliderPanel("footprint-panel");

    jQuery("#footprint").click(function() {
        FootprintManager.load();
        sliderPanel.show();
    });

    jQuery("#footprint-panel .panel-content").click(function(event) {
        var src = (event.srcElement || event.target);
        var ele = jQuery(src).closest("div.note-item");

        if(ele.size() < 1) {
            return;
        }
        sliderPanel.hide();
        document.getElementById("mainFrame").src = PageContext.getContextPath() + "/note/archive/edit.html?archiveId=" + ele.attr("archiveId");
    });
});

/**
 * 我的笔记本
 */
jQuery(function() {
    NoteBookManager.show(0, "我的笔记");

    var sliderPanel = new SliderPanel("notebook-panel");

    jQuery("#notebook").click(function() {
        NoteBookManager.load();
        sliderPanel.show();
    });

    jQuery("#notebook-panel .panel-content").click(function(event) {
        var src = (event.srcElement || event.target);
        var ele = jQuery(src).closest("div.book-item");

        if(ele.size() < 1) {
            return;
        }
        sliderPanel.hide();
        NoteBookManager.show(ele.attr("categoryId"), ele.attr("note-name"));
    });
});

/**
 * 分类目录
 */
jQuery(function() {
    jQuery("#note-dir").click(function() {

        if(jQuery("#tree-panel").is(":visible")) {
            jQuery("#tree-panel").hide();
            jQuery("#main-panel").css("marginLeft", 74);
        }
        else {
            jQuery("#tree-panel").show();
            jQuery("#main-panel").css("marginLeft", 424);
        }
    });
});

